package com.hogocloud.corelibrary.utils

import android.content.Context
import android.net.ConnectivityManager
import android.text.TextUtils
import com.hogocloud.corelibrary.LibConfig
import java.io.BufferedReader
import java.io.FileReader
import java.io.IOException

/**
 * Created by gjc on 2018-05-03.
 */
object NetWorkUtils {

    /**
     * 检查WIFI是否连接
     */
    fun isWifiConnected(): Boolean {
        val connectivityManager =
            LibConfig.getAppContext().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
        return wifiInfo.isConnected
    }

    /**
     * 检查手机网络(4G/3G/2G)是否连接
     */
    fun isMobileNetworkConnected(): Boolean {
        val connectivityManager =
            LibConfig.getAppContext().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val mobileNetworkInfo = connectivityManager
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
        return mobileNetworkInfo.isConnected
    }

    /**
     * 检查是否有可用网络
     */
    fun isNetworkConnected(): Boolean {
        val connectivityManager =
            LibConfig.getAppContext().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        return connectivityManager.activeNetworkInfo != null
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    fun getProcessName(pid: Int): String? {
        var reader: BufferedReader? = null
        try {
            reader = BufferedReader(FileReader("/proc/$pid/cmdline"))
            var processName = reader.readLine()
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim { it <= ' ' }
            }
            return processName
        } catch (throwable: Throwable) {
            throwable.printStackTrace()
        } finally {
            try {
                reader?.close()
            } catch (exception: IOException) {
                exception.printStackTrace()
            }

        }
        return null
    }
}
